<?php

class Ead_ListaexercicioController extends Ead_Controller_Action
{
    private $_table     = 'PUBLICACAO_LISTA';
    private $_pk        = 'PUL_ID';
    private $_order_col = 'PUL_DATENC DESC, PUL_HORENC';
    private $_order     = 'DESC';
    private $_sta_col   = 'PUL_STA';
    private $obj        = '';
    private $form       = '';
    
    
    public function init()
    {
         //if($this->getRequest()->getActionName() == 'edit') $this->form = new Admin_Form_Publicacaoead();       
    }
    
    public function indexAction() {
        
        Zend_Loader::loadClass('tools','library');
        Zend_Loader::loadClass('datetools','library');
        
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/ead/listaexercicio_list.js?1=2');
        
        $sessao = new Zend_Session_Namespace('Aluno');
        
        $this->view->aluno = $sessao->aluno;
        
        $where = ' AND a.ALU_ID = '.$sessao->aluno['ALU_ID'];
       
        
        $query = 'SELECT SQL_CACHE p.PUL_ID FROM '.$this->_table.' p, PUBLICACAO_LISTA_ALUNO a'
                .' WHERE p.PUL_ID = a.PUL_ID AND p.PUL_ANO = "'. date('Y').'" AND p.PUL_STA = 1'
                .' '.$where;
        $result = $this->db->fetchAll($query);
        foreach($result as $row) {
            $this->validaencerramento($row['PUL_ID']);
        }
        
        
        $query = 'SELECT SQL_CACHE p.*, a.ALU_ID FROM '.$this->_table.' p, PUBLICACAO_LISTA_ALUNO a '
                .' WHERE p.PUL_ID = a.PUL_ID AND p.PUL_ID = a.PUL_ID AND p.PUL_STA > 0'
                .' '.$where.' ORDER BY '.$this->_order_col.' '.$this->_order;
        $result = $this->db->fetchAll($query);
        $this->view->result = $this->paginacao($result);
        
        $this->db->closeConnection();  
    }
    
    public function editAction() {
        
        Zend_Loader::loadClass('tools','library');
        Zend_Loader::loadClass('datetools','library');
        Zend_Loader::loadClass('dominio','library');
        
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/jquery.maskMoney.js');
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/jquery.maskedinput.min.js');
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/mask.js');
        
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/validation/dist/jquery.validate.min.js');
        
        //$this->view->form = $this->form;
        if($this->getRequest()->isPost()) { 
            $formData = $this->getRequest()->getPost();
            try {
                if(1){//$this->form->isValid($formData)) {
                    
                    $this->db->beginTransaction();
                    
                    $id = $formData[$this->_pk];//(int) $this->form->getValue($this->_pk);
                    
                    //$data = $formData;//$this->form->getValues(); 
                    echo '<pre>';print_r($formData);
                        
                    $this->db->delete('PUBLICACAO_LISTA_RESPOSTA',$this->_pk.' = ' . $id.' AND ALU_ID = '.$formData['ALU_ID']);
                    if(isset($formData['q']))
                    foreach($formData['q'] as $key => $q){

                        $data = array(
                            'PLG_ID'    => strtoupper($formData['g'][$q]),
                            'PUL_ID'    => $id,
                            'ALU_ID'    => $formData['ALU_ID'],
                            'PLR_QST'   => $q,
                            'PLR_ALT'   => strtoupper($formData['a'][$q]),
                            'DCP_ID'    => strtoupper($formData['d'][$q]),
                        );
                        // desabilitado, agora so por ajax
                        //$this->db->insert('PUBLICACAO_LISTA_RESPOSTA',$data);
                    }
                    
                    $this->db->commit();
                    
                    $this->_helper->redirector('index');
                } else {
                    $this->view->data = $formData;
                }
            } catch(Exception $ex) {
                //echo $ex->getMessage();
                echo '<script>alert("'.$ex->getMessage().'");</script>';
                $this->view->data = $formData;
                $this->db->rollBack();
            }
        } else {
            $id = $this->_getParam('id', 0);
            if ($id > 0) {
                
                $data_enc = $this->validaencerramento($id);
                $this->view->data_enc = $data_enc;
                
                if($data_enc == FALSE){
                    $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/ead/listaexercicio.js?1='.rand(99,999));
                }
                
                $query = 'SELECT SQL_CACHE * FROM '.$this->_table.' WHERE '.$this->_pk . ' = ' . $id;
                $data = $this->db->fetchRow($query);
                $this->view->data = $data;
            }
        }
    }

    public function deleteAction() {
        $this->_helper->layout->disableLayout(); 
        $this->_helper->viewRenderer->setNoRender();  
        $ok = FALSE;
        $id = $this->_getParam('id', 0);
        if ((int)$id > 0 ) {   
            $this->db->beginTransaction();
            try {
                //$data = array($this->_sta_col => 0);
                //$ok = (bool) $this->obj->update($data, $this->_pk . ' = ' . $id);
                
                $query = 'SELECT SQL_CACHE TPC_ID FROM PUBLICACAO WHERE '.$this->_pk .' = '. $id;
                $row = $this->db->fetchRow($query);
                
                $query = 'SELECT SQL_CACHE a.ALC_ID, a.ALU_ID FROM ALUNO_CONTEUDO a, CONTEUDO c '
                        .' WHERE a.TPC_ID = c.TPC_ID AND a.CON_ID = c.CON_ID '
                        .' AND c.TPC_ID in('.$row['TPC_ID'].')';
                $result = $this->db->fetchAll($query);
                foreach($result as $row){
                    $this->db->delete('ALUNO_CONTEUDO','ALC_ID = ' . $row['ALC_ID']);
                }
                $ok = (bool) $this->db->delete('TOPICO_ALUNO',$this->_pk . ' = ' . $id);
                $ok = (bool) $this->db->delete($this->_table,$this->_pk . ' = ' . $id);
                
                $this->db->commit();
            } catch(Exception $ex) {
                //echo getMessage();
                $ok = FALSE;
                $msg = 'Não é possível excluir o material!';
                $this->db->rollBack();
            }      
        }       
        echo json_encode(array('ok' => $ok));
    }
    
    public function alternativaAction() {
        $this->_helper->layout->disableLayout(); 
        $this->_helper->viewRenderer->setNoRender();  
        $ok = FALSE;
        $msg = '';
        $ALU_ID = $this->_getParam('ALU_ID', 0);
        $PUL_ID = $this->_getParam('PUL_ID', 0);
        $PLG_ID = $this->_getParam('PLG_ID', 0);
        $DCP_ID = $this->_getParam('DCP_ID', 0);
        $num_qst = $this->_getParam('num_qst', 0);
        $qst_alt = $this->_getParam('qst_alt', '0');
        
        $ok = $this->validaencerramento($PUL_ID);
        
        if($ok == TRUE){ 
            $msg = 'Lista de teste finalizada!';
            echo json_encode(array('ok' => FALSE,'msg' => $msg));
            return '';
        }
        
        
        $where = ' PLG_ID = '.$PLG_ID.' AND PUL_ID = '.$PUL_ID.' AND ALU_ID = '.$ALU_ID. ' AND PLR_QST = '.$num_qst;
        $query = 'SELECT SQL_CACHE PLR_ID FROM PUBLICACAO_LISTA_RESPOSTA WHERE '.$where;
        $row = $this->db->fetchRow($query);
        
        $this->db->beginTransaction();
        try{
            
            $this->db->update('PUBLICACAO_LISTA_ALUNO',array('PLA_STA'=>'1'),'PUL_ID = '.$PUL_ID.' AND ALU_ID = '.$ALU_ID);
            
            if($row['PLR_ID'] > 0){
                $data = array(
                    'PLR_ALT' => $qst_alt,
                );
                $ok = (bool) $this->db->update('PUBLICACAO_LISTA_RESPOSTA',$data,'PLR_ID = '.$row['PLR_ID']);
            }else{
                $data = array(
                    'PLG_ID'    => $PLG_ID,
                    'PUL_ID'    => $PUL_ID,
                    'ALU_ID'    => $ALU_ID,
                    'PLR_QST'   => $num_qst,
                    'PLR_ALT'   => $qst_alt,
                    'DCP_ID'    => $DCP_ID,
                );
                //echo '<pre>';print_r($data);
                $ok = (bool) $this->db->insert('PUBLICACAO_LISTA_RESPOSTA',$data);
            }
            
            $this->db->commit();
            
        } catch(Exception $ex) {
            $msg = $ex->getMessage();
            $ok = FALSE;
            $this->db->rollBack();
        } 
        echo json_encode(array('ok' => $ok,'msg' => $msg));
                
        $this->db->closeConnection();       
    }
    
    public function confirmaralterarAction() { 
        $this->_helper->layout->disableLayout(); 
        $this->_helper->viewRenderer->setNoRender();  
        $ok = FALSE;
        $msg = '';
        $ALU_ID = $this->_getParam('ALU_ID', 0);
        $PUL_ID = $this->_getParam('PUL_ID', 0);
        $PLG_ID = $this->_getParam('PLG_ID', 0);
        $DCP_ID = $this->_getParam('DCP_ID', 0);
        $num_qst = $this->_getParam('num_qst', 0);
        $qst_alt = $this->_getParam('qst_alt', '0');
        $op = $this->_getParam('op', '0');
        
        $where = ' PLG_ID = '.$PLG_ID.' AND PUL_ID = '.$PUL_ID.' AND ALU_ID = '.$ALU_ID. ' AND PLR_QST = '.$num_qst;
        $query = 'SELECT SQL_CACHE PLR_ID FROM PUBLICACAO_LISTA_RESPOSTA WHERE '.$where;
        $row = $this->db->fetchRow($query);
        
        $this->db->beginTransaction();
        try{
            if($row['PLR_ID'] > 0){
                $data = array(
                    'PLR_STA' => $op,
                );
                $ok = (bool) $this->db->update('PUBLICACAO_LISTA_RESPOSTA',$data,'PLR_ID = '.$row['PLR_ID']);
            }
            
            $this->db->commit();
            
        } catch(Exception $ex) {
            $msg = $ex->getMessage();
            $ok = FALSE;
            $this->db->rollBack();
        } 
        echo json_encode(array('ok' => $ok,'msg' => $msg));
        
        $this->db->closeConnection();  
    }
    
    public function validaencerramento($PUL_ID){
        $ok = FALSE;
        $where = ' PUL_ID = '.$PUL_ID;
        $query = 'SELECT SQL_CACHE PUL_ID, PUL_DATENC, PUL_HORENC, PUL_STA FROM PUBLICACAO_LISTA WHERE '.$where;
        $row = $this->db->fetchRow($query);
        
        if($row['PUL_STA'] == 2){
            $ok = TRUE;
        }
        else if(strtotime($row['PUL_DATENC']) <= strtotime(date('Y-m-d'))){
            if(strtotime($row['PUL_HORENC']) < strtotime(date('H:i:s'))){
                $data['PUL_STA'] = 2;
                $this->db->update('PUBLICACAO_LISTA',$data,'PUL_ID = '.$row['PUL_ID']);
                $ok = TRUE;
                
                file_get_contents('http://'.$_SERVER['SERVER_NAME'].'/admin/funreport/gerarrelatoriolistadisalu');
            }   
        }
        else{
            $ok = FALSE;
        }
        
        return $ok;
        
        $this->db->closeConnection();  
    }
    
    public function verificaencerramentoAction() {
        $this->_helper->layout->disableLayout(); 
        $this->_helper->viewRenderer->setNoRender();  
        $ok = FALSE;
        $msg = '';
        $ALU_ID = $this->_getParam('ALU_ID', 0);
        $PUL_ID = $this->_getParam('PUL_ID', 0);
        
        $ok = $this->validaencerramento($PUL_ID);
        
        if($ok == TRUE) $msg = 'Lista de teste finalizada!';
        
        
        echo json_encode(array('ok' => $ok,'msg' => $msg));
    }
    
}